<template>
	<div class='userMaintain_container'>
		<div class='userMaintain_container_left'>
			<n-tree ref='treeRef' v-bind='leftTreeConfig'/>
		</div>
		<div class='userMaintain_container_right'>
			<vxe-grid ref='userMaintainGridRef' v-bind='tableConfig'>
				<template v-slot:form>
					<n-flex align='center' justify='space-evenly'>
						<n-form-item label='用户名' label-placement='left' :show-feedback='false'>
							<n-input v-model:value='tableConfig!.formConfig!.data.userName' type='text'
									 placeholder='请输入用户名' clearable/>
						</n-form-item>
						<n-form-item label='用户昵称' label-placement='left' :show-feedback='false'>
							<n-input v-model:value='tableConfig!.formConfig!.data.nickName' type='text'
									 placeholder='请输入用户昵称' clearable/>
						</n-form-item>
						<n-form-item :show-label='false' :show-feedback='false'>
							<n-button round strong :bordered='false'
									  type='success' @click='initRightTable'>
								搜索
							</n-button>
							<n-button round strong :bordered='false'
									  type='info' @click='reset'>
								重置
							</n-button>
						</n-form-item>
					</n-flex>
				</template>
				<template v-slot:toolbar_buttons>
					<n-button round strong @click='showAddModal'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-plus'/>
						</template>
						新增
					</n-button>
					<n-button round strong @click='resetPwd'>
						<template v-slot:icon>
							<SvgIcon icon-type='customized' icon-class='customized-resetPwd'/>
						</template>
						密码初始化
					</n-button>
				</template>
				<template v-slot:toolbar_tools>
					<div class='vxe-custom--wrapper'>
						<n-button circle @click='initRightTable'>
							<template v-slot:icon>
								<ClassIcon icon-class='fa fa-refresh'/>
							</template>
						</n-button>
						<!--<vxe-button
							circle icon='fa fa-download' title='导出Excel'
							@click='exportExcel'/>-->
					</div>
				</template>
				<template v-slot:operate='{ row }'>
					<n-button round strong @click='showEditModal(row)'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-edit'/>
						</template>
					</n-button>
					<n-button round strong @click='remove(row)'>
						<template v-slot:icon>
							<ClassIcon icon-class='fa fa-remove'/>
						</template>
					</n-button>
				</template>
			</vxe-grid>
		</div>
	</div>
	<addModal ref='addModalRef' v-bind='addModalConfig' :options='optionList'/>
	<editModal ref='editModalRef' v-bind='editModalConfig' :options='optionList'/>
	<!--<export-excel
		:id='"userMaintainExportExcel"' ref='exportExcel'
		:columns='columns'
		:pager-config='tableConfig["pagerConfig"]'
		:query-condition='tableConfig["formConfig"]["data"]' :query-id='"selectUserListByCommonPage"'/>-->
</template>
<script lang='ts' setup>
import { defineAsyncComponent, onBeforeMount, onMounted, reactive, ref } from 'vue';
import axios from '@/config/axios/index.ts';
import { VxeGrid, VxeUI } from '@/config/vxe/index.ts';
import { loadDict } from '@/config/dictionary/dictionary.ts';
import type { Dict } from '#/Dictionary.d.ts';
import { TreeInst, TreeOption, TreeProps } from 'naive-ui';
import { ModalEventTypes, VxeGridInstance, VxeGridProps } from 'vxe-table';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import type { UserProps } from '#/User.d.ts';
import type { Options } from '#/Options.d.ts';
const ClassIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/ClassIcon.vue'));
const SvgIcon = defineAsyncComponent(() => import('@/components/customComponents/icon/SvgIcon.vue'));
const dict = reactive<Dict>({});
const leftTreeConfig = reactive<TreeProps>({
	showLine            : true,
	animated            : true,
	accordion           : true,
	blockLine           : true,
	selectable          : true,
	virtualScroll       : true,
	expandOnClick       : false,
	showIrrelevantNodes : false,
	keyField            : 'deptCode',
	labelField          : 'deptAbbName',
	childrenField       : 'children',
	pattern             : '',
	selectedKeys        : [],
	data                : [],
	// nodeProps     : ({ option }: { option: TreeOption }) => {
	nodeProps : (params: any) => {
		return {
			onClick(event: MouseEvent) {
				// 阻止默认事件
				event.preventDefault();
				// 阻止传播
				event.stopPropagation();
				// 阻止即时传播
				event.stopImmediatePropagation();
				nodeClick(params.option);
			}
		};
	},
	// onLoad               : (node: TreeOption) => initLeftTree(node),
	onUpdateExpandedKeys : (
		keys: Array<string | number>,
		option: Array<TreeOption | null>,
		meta: { node: TreeOption | null, action: 'expand' | 'collapse' | 'filter' }
	): void => {
	}
});
const tableConfig = reactive<VxeGridProps>({
	loading        : false,
	height         : 'auto',
	align          : 'center',
	rowConfig      : {
		keyField : 'userName'
	},
	checkboxConfig : {
		reserve : true
	},
	keyboardConfig : { isArrow : true },
	pagerConfig    : {
		currentPage : 1,
		pageSize    : 5,
		total       : 0
	},
	toolbarConfig  : {},
	formConfig     : {
		enabled : false,
		data    : {
			tenantCode : null,
			deptCode   : null,
			userName   : null,
			nickName   : null,
			status     : null
		}
	},
	columns        : [
		{
			type : 'checkbox'
		},
		{
			field        : 'userName',
			title        : '用户名',
			showOverflow : 'tooltip',
			sortable     : true
		},
		{
			field        : 'nickName',
			title        : '员工姓名',
			showOverflow : 'tooltip',
			sortable     : true
		},
		{
			field        : 'phone',
			title        : '手机号',
			showOverflow : 'tooltip',
			sortable     : true
		},
		{
			field        : 'status',
			title        : '账号状态',
			showOverflow : 'tooltip',
			sortable     : true,
			cellRender   : {
				name   : 'n-switch',
				props  : {
					size           : 'large',
					checkedValue   : true,
					uncheckedValue : false,
					slots          : {
						checked   : '启用',
						unchecked : '禁用'
					}
				},
				events : {
					toggleEvent : async (row: any) => toggleStatus(row)
				}
			}
		},
		{
			title        : '操作',
			showOverflow : 'tooltip',
			slots        : {
				// 使用 JSX 渲染
				default : 'operate'
			}
		}
	],
	data           : [],
	// @ts-ignore
	onPageChange : (params: any) => changePage(params),
	// @ts-ignore
	onFormSubmit : () => queryCondition()
});
const currentSelectedDept = ref('');
// 新增模态框组件引入
const addModal = defineAsyncComponent(() => import('./addModal.vue'));
// 编辑模态框组件引入
const editModal = defineAsyncComponent(() => import('./editModal.vue'));
const props = defineProps({
	params : {
		type    : Object,
		require : false,
		default : null
	}
});
const addModalConfig = reactive({
	initTable : () => initRightTable(),
	dict      : dict
});
const editModalConfig = reactive({
	initTable : () => initRightTable(),
	dict      : dict
});
// 树引用
const treeRef = ref<TreeInst>();
// 右侧表格引用
const userMaintainGridRef = ref<VxeGridInstance>();
// 新增模态框引用
const addModalRef = ref<InstanceType<typeof addModal>>();
// 编辑模态框引用
const editModalRef = ref<InstanceType<typeof editModal>>();
const optionList = reactive<Options>({
	deptList : {
		loading     : false,
		disabled    : false,
		placeholder : '请选择部门',
		list        : [],
		map         : {}
	},
	roleList : {
		loading     : false,
		disabled    : false,
		placeholder : '请选择角色',
		list        : [],
		map         : {}
	}
});
onBeforeMount(() => {
	initAll();
});
onMounted(() => {
	initLeftTree();
	initRightTable();
});
const initAll = async () => {
	tableConfig!.formConfig!.data.tenantCode = sessionStorage.getItem('loginTenantCode');
	// 加载字典
	loadDict(['userStatus']).then((jsonResult: unknown) => {
		// 合并字典
		Object.assign(dict, jsonResult);
	});
	await initOptionList();
};
const initOptionList = async () => {
	Promise.all([
		axios.post('/department/optionList', {
			tenantCode : sessionStorage.getItem('loginTenantCode')
		}),
		axios.post('/role/optionList', {
			tenantCode : sessionStorage.getItem('loginTenantCode')
		})
		// @ts-ignore
	]).then((jsonResult: Array<JsonResultProps<any>>) => {
		const jsonResult1 = jsonResult[0];
		const jsonResult2 = jsonResult[1];
		if (jsonResult1.status && jsonResult2.status) {
			// 将禁用和加载状态解除
			optionList.deptList.list = jsonResult1.data;
			optionList.deptList.disabled = false;
			// 将禁用和加载状态解除
			optionList.roleList.list = jsonResult2.data;
			optionList.roleList.disabled = false;
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const initLeftTree = async () => {
	return new Promise<void>((resolve, reject) => {
		axios<any, JsonResultProps<any>, any>({
			method : 'POST',
			url    : '/department/list',
			data   : {
				tenantCode : sessionStorage.getItem('loginTenantCode'),
				deptCode   : null
			}
		}).then((jsonResult: JsonResultProps<any>) => {
			if (jsonResult['status']) {
				leftTreeConfig['data'] = jsonResult['data'];
			} else {
				VxeUI.modal.message({
					content : jsonResult['msg'],
					status  : 'warning',
					id      : 'failedMessage'
				});
			}
		}).catch((error: unknown) => {
			reject();
			console.error(error);
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
		});
	});
};
const nodeClick = async (option: TreeOption) => {
	// leftTreeConfig['currentClickNodeKey'] = option['key'];
	// 如果已选中该部门则不处理
	if (currentSelectedDept.value === option['deptCode']) {
		return;
	}
	currentSelectedDept.value = option['deptCode'] as string;
	tableConfig['formConfig']!['data']!['deptCode'] = option['deptCode'] as string;
	await initRightTable();
};
const initRightTable = async () => {
	tableConfig['loading'] = true;
	userMaintainGridRef.value?.clearCurrentRow();
	userMaintainGridRef.value?.clearCurrentColumn();
	tableConfig!.formConfig!.data = {
		...tableConfig!.formConfig!.data,
		pageNum  : tableConfig['pagerConfig']!['currentPage'],
		pageSize : tableConfig['pagerConfig']!['pageSize']
	};
	axios<any, JsonResultProps<any>, any>({
		method : 'POST',
		url    : '/user/pagingList',
		data   : tableConfig['formConfig']!['data']
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			tableConfig['pagerConfig']!['total'] = jsonResult['data']['total'];
			tableConfig['data'] = jsonResult['data']['records'];
			tableConfig['loading'] = false;
		} else {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const queryCondition = async () => {
	await initRightTable();
};
const changePage = async ({ currentPage, pageSize }: { currentPage: number, pageSize: number }) => {
	tableConfig['pagerConfig']!['currentPage'] = currentPage;
	tableConfig['pagerConfig']!['pageSize'] = pageSize;
	initRightTable();
};
const reset = async () => {
	tableConfig!.formConfig!.data.tenantCode = sessionStorage.getItem('loginTenantCode');
	tableConfig!.formConfig!.data.userName = null;
	tableConfig!.formConfig!.data.nickName = null;
	tableConfig!.formConfig!.data.deptCode = null;
	tableConfig!.formConfig!.data.status = null;
	await initRightTable();
};
const toggleStatus = async (rowData: UserProps) => {
	axios<any, JsonResultProps<any>, any>({
		method : 'PATCH',
		url    : `/user/status/${rowData.tenantCode}/${rowData.userName}`
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult['status']) {
			initRightTable();
		} else {
			VxeUI.modal.message({
				content : jsonResult['msg'],
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const showAddModal = async () => {
	// 判断是否选中了左侧的部门
	if (currentSelectedDept.value) {
		addModalRef.value!.showModal(currentSelectedDept.value);
	} else {
		VxeUI.modal.message({ content : '请先选择一个部门!', status : 'warning', id : 'deptNotSelectedMessage' });
	}
};
const showEditModal = async (row: unknown) => {
	editModalRef.value!.showModal(row);
};
const resetPwd = async (row: any) => {
	VxeUI.modal.confirm({
		content : '您确定要重置该账号的密码吗?',
		title   : '确认重置',
		id      : 'resetPwdModalUnique'
	}).then((type: ModalEventTypes): boolean | void => {
		if ('confirm' === type) {
			const currentCheckedList = userMaintainGridRef.value!.getCheckboxRecords(true).map((item: any) => {
				return item.userName;
			});
			const reserveCheckedList = userMaintainGridRef.value!.getCheckboxReserveRecords(true).map((item: any) => {
				return item.userName;
			});
			const userNameList = [
				...currentCheckedList,
				...reserveCheckedList
			];
			console.log(currentCheckedList);
			console.log(reserveCheckedList);
			axios<any, JsonResultProps<any>, any>({
				method : 'PATCH',
				url    : `/user/resetPwd`,
				data   : {
					tenantCode   : sessionStorage.getItem('loginTenantCode'),
					userNameList : userNameList
				}
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					initRightTable();
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
const remove = async (row: any) => {
	VxeUI.modal.confirm({
		content : '您确定要删除该数据吗?',
		title   : '确认删除',
		id      : 'deleteModalUnique'
	}).then((type: ModalEventTypes): boolean | void => {
		if ('confirm' === type) {
			axios<any, JsonResultProps<any>, any>({
				method : 'DELETE',
				url    : `/user/remove/${sessionStorage.getItem('loginTenantCode')}/${row.userName}`
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					initRightTable();
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
</script>
<style lang='scss' scoped>
.userMaintain_container{
	margin          :0;
	padding         :0;
	border          :0;
	width           :100%;
	height          :100%;
	display         :flex;
	flex-direction  :row;
	flex-wrap       :nowrap;
	align-content   :center;
	justify-content :center;
	align-items     :flex-start;
	.userMaintain_container_left{
		width      :20%;
		height     :100%;
		padding    :10px;
		text-align :center;
		overflow-y :auto;
	}
	.userMaintain_container_right{
		width  :80%;
		height :100%;
	}
}
</style>